package com.zm.spring.aop.Proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

//基于继承实现
//cglib 动态字节码技术
public class CGLIB {

    public static void main(String[] args) {
        人 person = new 房东();
        人 proxyObject = proxy(person);
        proxyObject.say();
    }
    public static <T> T proxy(T target){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback((new MethodInterceptor() {
            @Override
            public Object intercept(Object proxy,  //代理对象
                                    Method method, //方法对象
                                    Object[] args, //参数数组
                                    MethodProxy methodProxy
            ) throws Throwable {
                try {
                    System.out.println("前置增强");
                    Object ret = method.invoke(target, args);
                    System.out.println("返回增强");
                    return ret;
                } catch (Exception e) {
                    System.out.println("异常增强");
                    throw new RuntimeException(e);
                } finally {
                    System.out.println("后置增强");
                }
            }
        }));
        Object proxyObject = enhancer.create();
        return (T) proxyObject;

    }
}
